package com.showcai.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.showcai.dao.AdvertLocationMapper;
import com.showcai.dao.AdvertMapper;
import com.showcai.module.Advert;
import com.showcai.module.AdvertLocation;
import com.showcai.module.BaseModule;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.service.AdvertService;
import com.showcai.service.ServiceBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2018-9-5.
 */
@Service
public class AdvertServiceImpl extends ServiceBase implements AdvertService {

    @Autowired
    AdvertMapper advertMapper;
    @Autowired
    AdvertLocationMapper advertLocationMapper;


    @Override
    public Advert getAdvertById(Long tid) throws MyRunTimeExcption {
        return advertMapper.getAdvertByTid(tid);
    }

    @Override
    public List<Advert> getAdvertBylocationId(Long locationId) throws MyRunTimeExcption {
        return advertMapper.getAdvertBylocationId(locationId);
    }

    @Override
    public void modifyAdvert(Advert advert) throws MyRunTimeExcption {
        if (advert.getTid() == null) {
            insert(advert);
            return;
        }
        update(advert);
    }

    @Override
    public PageInfo getAdvertList(Map<String, String> map) throws MyRunTimeExcption {
        Integer page = Integer.parseInt(map.get("page"));
        Integer pageSize = Integer.parseInt(map.get("pageSize"));
        PageHelper.startPage(page,pageSize);
        List<Advert> list = advertMapper.getAdvertPageList();
        PageInfo pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void stopAdvert(Long tid) throws MyRunTimeExcption {
        Advert advert = new Advert();
        advert.setTid(tid);
        advert.setStatus(BaseModule.STATUS_UNVALID);
        advertMapper.updateAdvertPrimaryKeySelective(advert);
    }

    @Override
    public void operateAdvert(Long tid) throws MyRunTimeExcption  {
        Advert advert = new Advert();
        advert.setTid(tid);
        advert.setStatus(BaseModule.STATUS_VALID);
        advertMapper.updateAdvertPrimaryKeySelective(advert);
    }

    private Advert insert(Advert advert)  {
        advert.setCreateTime(new Date());
        advertMapper.insertAdvert(advert);
        return advert;
    }

    private void update(Advert advert) {
        advertMapper.updateAdvertPrimaryKeySelective(advert);
    }

    @Override
    public List<AdvertLocation> selectAdvertLocationList(Map<String, String> map) throws MyRunTimeExcption {
        return advertLocationMapper.selectAdvertLocationList(map);
    }
}

